Count repeated characters - collections¶
Count repeated characters in a string.
Sample string:
‘thequickbrownfoxjumpsoverthelazydog’
Expected output :
o 4
e 3
u 2
h 2
r 2
t 2
import collections
S = 'thequickbrownfoxjumpsoverthelazydog'
d = collections.defaultdict(int)
for c in S:
d[c] += 1
# print(d) # defaultdict(<class 'int'>, {'t': 2, 'h': 2, 'e': 3, ...
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print('%s %d' % (c, d[c]))
Output:
o 4
e 3
t 2
h 2
u 2
r 2